package com.sen.ssp.common.interceptors;

import java.util.Map;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.sen.common.utils.net.Encoder;
import com.sen.ssp.common.session.SessionFetcher;

/**
 * session拦截器，判断用户是否已登陆。
 * 
 * @author sen
 */
public final class SessionInterceptor extends BaseInterceptor {

	private static final long serialVersionUID = 4213745163539945816L;
	private static Logger LOG = Logger.getLogger(SessionInterceptor.class);

	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> sessionMap = ActionContext.getContext().getSession();
		String sessionUserName = SessionFetcher.from(sessionMap).getUserName();

		// 跳转处理
		if (sessionUserName != null || isIgnoredSession(invocation.getInvocationContext().getName())) {
			return invocation.invoke();
		}

		String sessionOutMessage = "您还没有登录或登陆超时，请重新登陆！";
		if (LOG.isInfoEnabled()) {
			LOG.info(sessionOutMessage);
		}

		// ajax处理
		if (isAjaxRequest()) {
			setErrorTipMessage(TIMEOUT_TYPE, Encoder.encode(sessionOutMessage));
			return Action.NONE;
		}

		ActionContext.getContext().put("sessionOutMessage", sessionOutMessage);
		return "timeout";
	}

	private boolean isIgnoredSession(String actionName) {
		return "login".equals(actionName) || "logout".equals(actionName);
	}

}
